new Vue({
    el: '#app',
    data: {
        searchQuery: '',
        user: {
            name: '管理员',
            avatar: 'https://randomuser.me/api/portraits/men/41.jpg'
        },
        products: [],
        newProduct: {
            name: '',
            category: '',
            price: 0,
            stock: 0,
            status: 'active',
            image: '',
            description: ''
        },
        editingProduct: {
            name: '',
            category: '',
            price: 0,
            stock: 0,
            status: 'active',
            image: '',
            description: ''
        },
        addModalVisible: false,
        editModalVisible: false,
        //分类列表
        categories: []
    },
    computed: {
        filteredProducts() {
            console.log(this.products);
            if (!this.products || this.products.length === 0) return [];
            if (this.searchQuery === '') return this.products;
            const query = this.searchQuery;
            console.log(this.categories);
            
            return this.products.filter(p =>
                p.name.includes(query) 
            )
        }
    },
    mounted() {
        this.fetchProducts();
        this.getAllClassfiy();

    },
    methods: {
        openAddModal() {
            this.addModalVisible = true;
        },
        closeAddModal() {
            this.addModalVisible = false;
            // 重置表单
            this.newProduct = {
                name: '',
                category: '',
                price: 0,
                stock: 0,
                status: 'active',
                image: '',
                description: ''
            };
        },

        triggerFileInput() {
            console.log('triggerFileInput');

            this.$refs.fileInput.click();
        },
        triggerEditedFileInput() {
            this.$refs.editFileInput.click();
        },
        // 图片上传
        handleImageUpload(event) {
            const file = event.target.files[0];
            if (file) {
                this.newProduct.image = URL.createObjectURL(file); // 预览图
                this.newProduct.imageFile = file; // 保留原始文件
            }
        },
        // 添加商品d
        addProduct() {

            const productData = {
                commodityName: this.newProduct.name,
                classifyId: this.newProduct.category,
                commoditySalePrice: this.newProduct.price,
                commodityNum: this.newProduct.stock,
                commodityDesc: this.newProduct.description

            };
            

            $.ajax({
                url: 'http://localhost:8080/productManage/addCommodity',
                type: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(productData),
                headers: { token: userId = 1 },
                success: (res) => {
                    if (res.code === 200 && res.data && this.newProduct.imageFile) {
                        const productId = res.data; // 假设返回商品ID为 productId
                        this.uploadImage(productId, this.newProduct.imageFile);
                    }
                    
                    alert('商品添加成功！');
                },
                error: (err) => {
                    alert('添加失败: ' + err || '网络错误');
                }
            });

        },
        // 上传图片
        uploadImage(productId, file) {
            const formData = new FormData();
            formData.append('commodityPic', file);

            $.ajax({
                url: `http://localhost:8080/productManage/addCommodityPic?commodityId=${productId}`,
                type: 'POST',
                data: formData,
                headers: { token: userId = 1 },
                processData: false,
                contentType: false,
                success: (res) => {
                    if (res.code !== 200) {
                        alert('图片上传失败，请手动重试');
                    }
                    this.closeAddModal();
                    this.fetchProducts();
                },
                error: (err) => {
                    alert('图片上传失败: ' + err.responseText || '网络错误');
                }
            });
        },
        //打开修改模态框
        openEditModal(product) {
            // 深拷贝商品对象，避免直接修改原始数据
            this.editingProduct = JSON.parse(JSON.stringify(product));

            this.editModalVisible = true;
        },
        //关闭修改模态框
        closeEditModal() {
            this.editModalVisible = false;
            this.editingProduct = {};
        },
        // 修改商品图片
        handleEditImageUpload(event) {

            const file = event.target.files[0];
            if (file) {
                this.editingProduct.image = URL.createObjectURL(file); // 预览图
                this.editingProduct.imageFile = file; // 保留原始文件
            }
        },
        updateProduct() {
            // 找到要更新的商品索引
            const index = this.products.findIndex(p => p.id === this.editingProduct.id);
            console.log(this.editingProduct);

            if (index !== -1) {
                // 更新商品信息
                this.products.splice(index, 1, this.editingProduct);
                const productData = {
                    commodityId: this.editingProduct.id,
                    commodityName: this.editingProduct.name,
                    commoditySalePrice: this.editingProduct.price,
                    commodityNum: this.editingProduct.stock,
                    commodityDesc: this.editingProduct.description,
                    classifyId: this.editingProduct.classifyId,
                    imageFile: this.editingProduct.imageFile
                };
                //上传服务器
                $.ajax({
                    url: 'http://localhost:8080/productManage/updateCommodity', // 后端接口地址
                    type: 'POST', // 请求方法
                    contentType: 'application/json', // 发送的数据类型
                    headers: { token: userId = 1 },
                    data: JSON.stringify(productData), // 将商品数据转换为 JSON 字符串
                    success: (response) => {
                        // 请求成功时的回调
                        if (response.code === 200) { // 假设后端返回 code 为 200 表示成功
                            // 如果有新的图片文件，则上传图片
                            if (productData.imageFile) {
                                this.updateProductImage(productData.commodityId, productData.imageFile);
                            }
                            // 关闭编辑模态框并刷新商品列表
                            this.closeEditModal();
                            this.fetchProducts();
                        } else {
                            alert('更新失败：' + response.message); // 显示后端返回的错误信息
                        }
                    },
                    error: function (xhr, status, error) {
                        // 请求失败时的回调
                        console.error('请求失败:', error);
                        alert('网络错误，请稍后再试');
                    }
                });

            }
        },
        //修改商品图片
        updateProductImage(id, file) {
            const formData = new FormData();
            formData.append('commodityPic', file);

            $.ajax({
                url: `http://localhost:8080/productManage/updateCommodityPic?commodityId=${id}`,
                type: 'POST',
                data: formData,
                headers: { token: userId = 1 },
                processData: false,
                contentType: false,
                success: (res) => {
                    if (res.code !== 200) {
                        alert('图片上传失败，请手动重试');
                    }
                },
                error: (err) => {
                    alert('图片上传失败: ' + err.responseText || '网络错误');
                }
            });
        },
        deleteProduct(id) {
            if (confirm('确定要删除这个商品吗？此操作不可撤销。')) {
                // 过滤掉被删除的商品
                this.products = this.products.filter(p => p.id !== id);
                $.ajax({
                    url: 'http://localhost:8080/productManage/updateCommodityStatus',
                    type: 'POST',
                    data: {
                        commodityId:id,
                        commodityStatus: 2
                    },
                    headers: { token: userId = 1 },
                    success: (res) => {
                        alert('商品已成功删除！');
                    },
                    error: (res) => {
                        alert('网络错误，操作失败。');
                    }
                })

            }
        },
        // 切换商品状态
        toggleProductStatus(product) {
            // 切换状态：1 为上架，0 为下架
            product.status = product.status === 1 ? 0 : 1;
            $.ajax({
                url: 'http://localhost:8080/productManage/updateCommodityStatus',
                type: 'POST',
                data: {
                    commodityId: product.id,
                    commodityStatus: product.status
                },
                headers: { token: userId = 1 },
                success: (res) => {
                    const action = product.status === 1 ? '上架' : '下架';
                    alert(`商品已${action}`);
                },
                error: (res) => {
                    alert('网络错误，操作失败。');
                }
            })


        },
        //获取所有商品数据
        fetchProducts() {
            $.ajax({
                url: 'http://localhost:8080/productManage/getAllCommodity',
                type: 'GET',
                headers: { token: userId = 1 },
                success: (data) => {
                    if (data.code === 200 && Array.isArray(data.data)) {
                        console.log('获取商品列表成功:', data);
                        this.products = data.data.map(item => ({
                            id: item.commodityId,
                            name: item.commodityName,
                            price: item.commoditySalePrice,
                            stock: item.commodityNum,
                            status: item.commodityStatus,
                            image: "http://localhost:8080" + item.commodityPicture[0].commodityImageUrl || 'https://via.placeholder.com/60x60?text=No+Image',
                            classifyId: item.classify.classifyId,
                            description: item.commodityDesc

                        }));
                        console.log(this.products);

                    } else {
                        alert('加载商品数据失败');
                        console.error('接口返回异常:', data);
                    }

                },
                error: function (err) {
                    console.log(err);
                }
            })
        },
        //获取分类数据
        getAllClassfiy() {
            var settings = {
                "url": "http://localhost:8080/productManage/getAllClassify",
                "method": "GET",
                "timeout": 0,
                "headers": {
                    "token": "userId=1",
                    "User-Agent": "Apifox/1.0.0 (https://apifox.com)",
                    "Accept": "*/*",
                    "Host": "localhost:8080",
                    "Connection": "keep-alive"
                },
            };

            $.ajax(settings).done((response) => {
                this.categories = response.data
                console.log(this.categories);
            });
        },
       
    }
});